package com.example.i2v.controller;

import com.example.i2v.model.TaskQueryResponse;
import com.example.i2v.model.VideoGenerationRequest;
import com.example.i2v.model.VideoGenerationResponse;
import com.example.i2v.service.VideoGenerationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 视频生成控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/video")
@CrossOrigin(origins = "*")
public class VideoGenerationController {

    @Autowired
    private VideoGenerationService videoGenerationService;



    /**
     * 创建任务并等待完成（组合接口）
     */
    @PostMapping("/generateAndWait")
    public ResponseEntity<Map<String, Object>> generateVideoAndWait(@Valid @RequestBody VideoGenerationRequest request) {
        log.info("收到视频生成并等待请求: {}", request.getInput().getPrompt());
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            TaskQueryResponse response = videoGenerationService.createTaskAndWait(request);
            
            if (response.getCode() != null) {
                // 有错误码，说明请求失败
                result.put("success", false);
                result.put("code", response.getCode());
                result.put("message", response.getMessage());
                return ResponseEntity.badRequest().body(result);
            }
            
            result.put("success", true);
            result.put("taskId", response.getOutput().getTaskId());
            result.put("taskStatus", response.getOutput().getTaskStatus());
            result.put("submitTime", response.getOutput().getSubmitTime());
            result.put("scheduledTime", response.getOutput().getScheduledTime());
            result.put("endTime", response.getOutput().getEndTime());
            result.put("videoUrl", response.getOutput().getVideoUrl());
            result.put("origPrompt", response.getOutput().getOrigPrompt());
            result.put("actualPrompt", response.getOutput().getActualPrompt());
            result.put("requestId", response.getRequestId());
            
            if (response.getUsage() != null) {
                result.put("usage", response.getUsage());
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("创建任务并等待完成失败", e);
            result.put("success", false);
            result.put("message", "任务执行失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "DashScope I2V Video Generation Service");
        result.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(result);
    }
}